<template>
  <div class="cart-container">
    <h2>我的购物车</h2>
    
    <div v-if="cartItems.length === 0" class="empty-cart">
      <p>购物车是空的</p>
      <router-link to="/dashboard/drugs" class="continue-shopping">
        继续购物
      </router-link>
    </div>

    <div v-else class="cart-content">
      <div class="cart-items">
        <div v-for="item in cartItems" :key="item.id" class="cart-item">
          <img :src="item.image" :alt="item.name" class="item-image">
          <div class="item-info">
            <h3>{{ item.name }}</h3>
            <p class="price">¥{{ item.price }}</p>
            <div class="quantity-control">
              <button 
                @click="updateQuantity(item, -1)"
                :disabled="item.quantity <= 1"
              >-</button>
              <span>{{ item.quantity }}</span>
              <button 
                @click="updateQuantity(item, 1)"
                :disabled="item.quantity >= item.stock"
              >+</button>
            </div>
          </div>
          <div class="item-actions">
            <button @click="removeItem(item)" class="remove-btn">
              删除
            </button>
          </div>
        </div>
      </div>

      <div class="cart-summary">
        <div class="summary-item">
          <span>商品总数：</span>
          <span>{{ totalItems }}件</span>
        </div>
        <div class="summary-item">
          <span>总价：</span>
          <span class="total-price">¥{{ totalPrice }}</span>
        </div>
        <button @click="checkout" class="checkout-btn">
          结算
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { API_ENDPOINTS } from '../api/config';
import axios from 'axios';

export default {
  name: 'ShoppingCart',
  data() {
    return {
      cartItems: []
    };
  },
  computed: {
    totalItems() {
      return this.cartItems.reduce((sum, item) => sum + item.quantity, 0);
    },
    totalPrice() {
      return this.cartItems.reduce((sum, item) => sum + item.price * item.quantity, 0).toFixed(2);
    }
  },
  methods: {
    async fetchCartItems() {
      try {
        const userInfo = JSON.parse(localStorage.getItem('user') || '{}');
        if (!userInfo.id) {
          this.$router.push('/');
          return;
        }

        const response = await axios.get(API_ENDPOINTS.CART.GET);
        this.cartItems = response.data;
      } catch (error) {
        console.error('获取购物车失败:', error);
        alert('获取购物车失败');
      }
    },
    async updateQuantity(item, change) {
      try {
        const newQuantity = item.quantity + change;
        if (newQuantity < 1 || newQuantity > item.stock) return;

        await axios.put(API_ENDPOINTS.CART.UPDATE_QUANTITY(item.drug_id), {
          quantity: newQuantity
        });

        item.quantity = newQuantity;
        // 更新购物车数量
        this.$emit('cart-count-updated', this.totalItems);
      } catch (error) {
        console.error('更新数量失败:', error);
        // 只在真正出错时显示错误提示
        if (error.response && error.response.status !== 200) {
          alert('更新数量失败，请重试');
        }
      }
    },
    async removeItem(item) {
      try {
        const response = await axios.delete(API_ENDPOINTS.CART.REMOVE(item.drug_id));
        
        if (response.data && response.data.success) {
          this.cartItems = this.cartItems.filter(i => i.drug_id !== item.drug_id);
          // 更新购物车数量
          this.$emit('cart-count-updated', this.totalItems);
        } else {
          alert(response.data?.message || '删除商品失败');
        }
      } catch (error) {
        console.error('删除商品失败:', error);
        if (error.response?.data?.message) {
          alert(error.response.data.message);
        } else {
          alert('删除商品失败，请重试');
        }
      }
    },
    async checkout() {
      try {
        // 检查所有商品的库存
        for (const item of this.cartItems) {
          if (item.quantity > item.stock) {
            alert(`商品 ${item.name} 的购买数量超过库存`);
            return;
          }
        }

        // 调用结算接口
        const response = await axios.post(API_ENDPOINTS.CART.CHECKOUT);
        
        if (response.data && response.data.success) {
          alert('购买成功');
          this.cartItems = [];
          // 更新购物车数量
          this.$emit('cart-count-updated', this.totalItems);
          // 跳转到订单列表
          this.$router.push('/dashboard/orders');
        } else {
          alert(response.data?.message || '结算失败');
        }
      } catch (error) {
        console.error('结算失败:', error);
        if (error.response?.data?.message) {
          alert(error.response.data.message);
        } else {
          alert('结算失败，请重试');
        }
      }
    }
  },
  created() {
    this.fetchCartItems();
  }
};
</script>

<style scoped>
.cart-container {
  padding: 20px;
  min-height: calc(100vh - 120px); /* 假设头部等占据120px的高度 */
}

.empty-cart {
  text-align: center;
  padding: 40px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.continue-shopping {
  display: inline-block;
  margin-top: 20px;
  padding: 10px 20px;
  background-color: #42b983;
  color: white;
  text-decoration: none;
  border-radius: 4px;
}

.cart-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
}

.cart-items {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.cart-item {
  display: flex;
  gap: 20px;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.cart-item:last-child {
  border-bottom: none;
}

.item-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
}

.item-info {
  flex: 1;
}

.item-info h3 {
  margin: 0 0 10px 0;
  color: #2c3e50;
}

.price {
  color: #e74c3c;
  font-size: 1.2em;
  font-weight: bold;
  margin: 10px 0;
}

.quantity-control {
  display: flex;
  align-items: center;
  gap: 10px;
}

.quantity-control button {
  width: 30px;
  height: 30px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.quantity-control button:hover:not(:disabled) {
  background: #f8f9fa;
  border-color: #42b983;
}

.quantity-control button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.quantity-control span {
  min-width: 30px;
  text-align: center;
}

.item-actions {
  display: flex;
  align-items: center;
}

.remove-btn {
  padding: 8px 16px;
  background-color: #dc3545;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.remove-btn:hover {
  background-color: #c82333;
}

.cart-summary {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  align-self: start;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  font-size: 1.1em;
}

.total-price {
  color: #e74c3c;
  font-weight: bold;
  font-size: 1.2em;
}

.checkout-btn {
  width: 100%;
  padding: 12px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1.1em;
  cursor: pointer;
  transition: background-color 0.3s;
}

.checkout-btn:hover {
  background-color: #3aa876;
}
</style> 